import { PrismaClient } from '@prisma/client';
import { RegisterInput, LoginInput } from '../dto/user.dto';
import { hashPassword, verifyPassword } from '../utils/password';
import { HttpError } from '../utils/httpError';
import { ErrorCode } from '../constants/errorCode';

const prisma = new PrismaClient();

export const register = async (input: RegisterInput) => {
  const { username, email, phone } = input;

  // 检查重复项
  const existing = await prisma.users.findFirst({
    where: {
      OR: [
        { username },
        { email: email || '' },
        { phone: phone || '' }
      ]
    }
  });

  if (existing) {
    throw new HttpError(ErrorCode.USER_EXIST, 409);
  }

  const user = await prisma.users.create({
    data: {
      username: input.username,
      password: await hashPassword(input.password),
      email: input.email,
      phone: input.phone,
      avatar: input.avatar,
      bio: input.bio
    }
  });

  return user;
};

export const login = async (input: LoginInput) => {
  const { account, password } = input;

  // 多方式登录匹配：用户名、邮箱或手机号
  const user = await prisma.users.findFirst({
    where: {
      OR: [
        { username: account },
        { email: account },
        { phone: account }
      ]
    }
  });

  if (!user) {
    throw new HttpError(ErrorCode.USER_NOT_FOUND, 404);
  }

  const valid = await verifyPassword(password, user.password);
  if (!valid) {
    throw new HttpError(ErrorCode.PASSWORD_INCORRECT, 401);
  }

  return user;
};
